<?php


namespace app\api\controller;
use app\api\model\Base as bs;
use lib\PHPMailer;
use think\Db;
use think\Request;

class Email
{
    public static $Host = 'smtp.163.com'; //smtp服务器
    private static $From = 'leeyamaster@163.com'; //发送者的邮件地址
    private static $FromName = 'leeya'; //发送邮件的用户昵称
    private static $Username = 'leeyamaster@163.com'; //登录到邮箱的用户名
    private static $Password = 'UEXKCMABLBNVSKKE'; //第三方登录的授权码，在邮箱里面设置
    public function email(){
        if(Request::instance()->method()== 'POST'){
            $value = I('username|email');
            $data = Db::name('user')->where('status',1)
                ->where('username', $value['username'])
                ->where('email', $value['email'])->find();
            if(empty($data)){
                $this->apiReturn(303,'账号或邮箱不存在',$data);
            }
            //获取token
            $admin = Db::table('user')->where(['username'=>$value['username']])->update(['token'=>getToken($data['username'],$data['permissions']),'update_time'=>time(),'expiration_time'=>time()+1200]);
            $admin ? 'true':'false';
            $user = Db::table('user')->field('id,username,token')->where(['username'=>$value['username']])->find();
            //发送邮件
            $title="方方抢课系统";
            $message="尊敬的".$value['username']."您的找回密码网址是localhost:8000/updatepassword?token=".$user['token'];
            $emailAddress=$value['email'];
            $mail = new PHPMailer();
            //3.设置属性，告诉我们的服务器，谁跟谁发送邮件
            $mail -> IsSMTP();			//告诉服务器使用smtp协议发送
            $mail -> SMTPAuth = true;		//开启SMTP授权
            $mail -> Host = self::$Host;	//告诉我们的服务器使用163的smtp服务器发送
            $mail -> From = self::$From;	//发送者的邮件地址
            $mail -> FromName = self::$FromName;		//发送邮件的用户昵称
            $mail -> Username = self::$Username;	//登录到邮箱的用户名
            $mail -> Password = self::$Password;	    //第三方登录的授权码，在邮箱里面设置
            //编辑发送的邮件内容
            $mail -> IsHTML(true);		    //发送的内容使用html编写
            $mail -> CharSet = 'utf-8';		//设置发送内容的编码
            $mail -> Subject = $title;//设置邮件的标题
            $mail -> MsgHTML($message);	//发送的邮件内容主体
            $mail -> AddAddress($emailAddress);    //收人的邮件地址
            //调用send方法，执行发送
            $result = $mail -> Send();
            if($result){
                $this->apiReturn(200,'发送成功请在20分内使用同一浏览器找回密码',['success'=>true,'token'=>$user['token']]);
            }else{
                $this->apiReturn(500,$mail -> ErrorInfo,['success'=>false]);
            }
        }

    }

    public function apiReturn( $code=200 , $msg='', $data = array() ,$total=0 ){
        $returnData = [
            'code' => $code,
            'msg'  => $msg?$msg:return_msg($code),
            'data' => $data,
            'total'=>$total,
        ];

        if(I('callback')){
            echo I('callback').'('.json_encode($returnData).')';die;
        }
        //$returnData[1] = decodeUnicode($returnData[1]);
        echo json_encode($returnData);die;
    }

}